package com.solcoo.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.solcoo.controller.AbstractController;
import com.solcoo.controller.JsonResult;
import com.solcoo.dao.DingDanDao;
import com.solcoo.dao.UseromrelaDao;
import com.solcoo.dao.YongHuDao;
import com.solcoo.dao.ZhangHuDao;
import com.solcoo.dao.ZheKouDao;
import com.solcoo.json.DingDanJson;
import com.solcoo.json.MonthStreamJson;
import com.solcoo.json.ReportJson;
import com.solcoo.json.ReportTypeJson;
import com.solcoo.pojo.DingDan;
import com.solcoo.pojo.Useromrela;
import com.solcoo.pojo.YongHu;
import com.solcoo.pojo.ZhangHu;
import com.solcoo.pojo.ZheKou;
import com.solcoo.util.SendMsgUtil;

@Service
public class DingDanService extends AbstractController {

	@Resource
    private ZheKouDao zheKouDao;
	@Resource
    private YongHuDao yongHuDao;
	@Resource
    private ZhangHuDao zhangHuDao;
	@Resource
    private DingDanDao dingDanDao;
    @Resource
    private UseromrelaDao useromrelaDao;

    private static Logger logger = Logger.getLogger(DingDanService.class);

    // 充值
    public JsonResult throwExcepshRecharge(DingDan dingdan, String shoujih, String isApp) throws Exception {
        YongHu yh = yongHuDao.selectUserByPhone(shoujih);
        
        if (yh == null)
            return this.getFailJsonResult("该用户不存在");

        // 查找商户
        String yhm = dingdan.getShanghuid() + "";
        while(yhm.length() < 5) {
            yhm = "0" + yhm;
        }
        YongHu sh = yongHuDao.selectUserByYonghum(yhm);

        // 判断是否为配送员操作
        String employeePh = null;
        if("3".equals(sh.getLeixing())) {
        	Useromrela ur = useromrelaDao.getEnabledEmployee(yhm);
        	if(ur != null) {
        		employeePh = sh.getShoujih();
        		dingdan.setHandlers(sh.getYonghum());
        		dingdan.setShanghuid(Integer.parseInt(ur.getOwnerid()));
        		sh = yongHuDao.selectUserByYonghum(ur.getOwnerid());
        	} else {
        		return this.getFailJsonResult("您的客户端已被禁用");
        	}
        }
        
        Integer gerenid = Integer.parseInt(yh.getYonghum()); // 卡号
        ZhangHu zh = zhangHuDao.query(dingdan.getShanghuid(), gerenid); // 账户
        
        BigDecimal incomeTotal = BigDecimal.valueOf(dingdan.getJine()).add(BigDecimal.valueOf(dingdan.getFreeAmount()));
        if (zh == null) {
        	// 增加商户中的关注人数
        	boolean operation = yongHuDao.addMemberCount(dingdan.getShanghuid());
            if ( !operation )
            	return this.getFailJsonResult("【充值】关注商户失败 (账户不存在)");

            zh = new ZhangHu();
            
            zh.setShanghuid(dingdan.getShanghuid());
            zh.setGerenid(gerenid);
            zh.setShifougz("1");
            zh.setYue(incomeTotal.doubleValue());
            zh.setJingyanz(dingdan.getJine());
            zh.setZongcz(incomeTotal.doubleValue());
            zh.setIncomeIntegrate(incomeTotal.doubleValue());
            zh.setDengji(0);
            zh.setZongxf(0);
            zh.setZhekoul(0);
            zh.setShNQCount(0);
            zh.setGrNQCount(0);
            
            zhangHuDao.add(zh);
        } else {
        	String shifougz = zh.getShifougz(); // 是否关注: 0-否  1-是
        	
        	if ( !"1".equals(shifougz) ) {
        		boolean operation = yongHuDao.addMemberCount(dingdan.getShanghuid());
        		
        		if ( !operation )
        			return this.getFailJsonResult("【充值】关注商户失败 (账户已存在)");
        		
        		zh.setShifougz("1");
        	}
        	
            zh.setYue(new BigDecimal(Double.toString(zh.getYue())).add(incomeTotal).doubleValue());
            zh.setIncomeIntegrate(BigDecimal.valueOf(zh.getIncomeIntegrate()).add(incomeTotal).doubleValue());
            zh.setJingyanz(new BigDecimal(Double.toString(zh.getJingyanz())).add(new BigDecimal(Double.toString(dingdan.getJine()))).doubleValue());
            zh.setZongcz(new BigDecimal(Double.toString(zh.getZongcz())).add(incomeTotal).doubleValue());
        }
        
        updateZhdj(zh);

        // 添加订单
        dingdan.setGerenid(gerenid);
        dingdan.setYue(zh.getYue());
        dingdan.setLeixing("1");
        dingdan.setShijian(new Date());
        
        dingDanDao.add(dingdan);
        
        // 推送和短信不在事务范围内
        try {
			// 维护推送相关数据
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("shanghuid", dingdan.getShanghuid());
			param.put("gerenid", gerenid);
			param.put("grNQCount", zh.getGrNQCount() + 1);
			param.put("shNQCount", zh.getShNQCount() + 1);
			zhangHuDao.updateNQCount(param);
			
			// 推送给商户
//			param.put("grNQCount", null);
//			TuiSong ts = new TuiSong();
//			Map<String, Integer> count = new HashMap<String, Integer>();
//			count.put(yh.getYonghum(), zhangHuDao.getShNQSum(param));
//			ts.setCount(count);
//			param.put("gerenid", null);
//			ts.setSum(zhangHuDao.getShNQSum(param));
			
			
			// 推送给个人
//			TuiSong ts2 = new TuiSong();
//			Map<String, Object> param2 = new HashMap<String, Object>();
//			param2.put("shanghuid", zh.getShanghuid());
//			param2.put("gerenid", zh.getGerenid());
//			param2.put("grNQCount", 1);
//			param2.put("shNQCount", null);
//			Map<String, Integer> count2 = new HashMap<String, Integer>();
//			count2.put(sh.getYonghum(), zhangHuDao.getGrNQSum(param2));
//			ts2.setCount(count2);
//			param2.put("shanghuid", null);
//			ts2.setSum(zhangHuDao.getGrNQSum(param2));
//			param2.put("grNQCount", null);
//			param2.put("shNQCount", 1);
			
//			JSONObject json = JSONObject.fromObject(ts);
//			JpushUtil ju1 = new JpushUtil(sh.getYonghum(), json.toString());
//			new Thread(ju1).start();
//			
//			JSONObject json2 = JSONObject.fromObject(ts2);
//			JpushUtil ju2 = new JpushUtil(yh.getYonghum(), json2.toString());
//			new Thread(ju2).start();
			
			// 发送短信
			if("1".equals(isApp)) {
				BigDecimal totalInComeAmount = BigDecimal.valueOf(dingdan.getJine()).add(BigDecimal.valueOf(dingdan.getFreeAmount()));
				
				// 给客户的短信
				String m = shoujih;
				String c = "您已在“"+sh.getDianming()+
				        "”充值"+totalInComeAmount.doubleValue()+"元，账户余额"+zh.getYue()+"元，" +
				        "等级"+zh.getDengji()+"级 ";
				
				// 给商户的短信
				m += "," + sh.getShoujih();
				c += "{|}" + "“" + yh.getYonghum() + 
						"”已在您店内充值"+totalInComeAmount.doubleValue()+"元，账户余额"+zh.getYue()+"元，" +
				        "等级"+zh.getDengji()+"级 ";
				
				if(employeePh!=null && !"".equals(employeePh)) {
					m += "," + employeePh;
					c += "{|}" + "“" + yh.getYonghum() + 
							"”已在您店内充值"+totalInComeAmount.doubleValue()+"元，账户余额"+zh.getYue()+"元，" +
					        "等级"+zh.getDengji()+"级 ";
				}
				SendMsgUtil sms = new SendMsgUtil(m, c);
				new Thread(sms).start();
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
    	
        String msg = yh.getNicheng() + "(搜卡号：" + yh.getYonghum() + ")\n"
                + "充　　值：" + incomeTotal.doubleValue() + "元\n"
                + "账户余额：" + zh.getYue()+"元\n"
                + "经验值提升" + zh.getJingyanz();
        return this.getSuccessJsonResult(msg);
    }

    // 支付
    public JsonResult throwExcepshPay(DingDan dingdan, String shoujih) throws Exception {
        YongHu yh = yongHuDao.selectUserByPhone(shoujih);
        
        if (yh == null)
            return this.getFailJsonResult("该用户不存在");

        // 查找商户
        String yhm = dingdan.getShanghuid() + "";
        while(yhm.length() < 5) {
            yhm = "0" + yhm;
        }
        YongHu sh = yongHuDao.selectUserByYonghum(yhm);

        // 判断是否为配送员操作
        String employeePh = null;
        if("3".equals(sh.getLeixing())) {
        	Useromrela ur = useromrelaDao.getEnabledEmployee(yhm);
        	if(ur != null) {
        		employeePh = sh.getShoujih();
        		dingdan.setHandlers(sh.getYonghum());
        		dingdan.setShanghuid(Integer.parseInt(ur.getOwnerid()));
        		sh = yongHuDao.selectUserByYonghum(ur.getOwnerid());
        	} else {
        		return this.getFailJsonResult("您的客户端已被禁用");
        	}
        }
        
        Integer yonghum = Integer.parseInt(yh.getYonghum()); // 卡号
        ZhangHu zh = zhangHuDao.query(dingdan.getShanghuid(), yonghum);
        
        // 账户不存在返回错误信息
        if (zh == null)
            return this.getFailJsonResult("该用户还不是您的会员");

        // 存在账户则修改及校验账户信息
        double yue = new BigDecimal(Double.toString(zh.getYue())).subtract(new BigDecimal(Double.toString(dingdan.getJine()))).doubleValue();
        
        // 余额小于 0，则返回错误信息
        if (yue < 0) {
            String msg = yh.getNicheng() + "(搜卡号：" + yh.getYonghum() + ")\n"
                    + "账户余额：" + zh.getYue() + "元";
            
            return this.getFailJsonResult("余额不足", msg);
        }
        
        // 关注商户
        String shifougz = zh.getShifougz(); // 是否关注: 0-否  1-是
        
        if ( !"1".equals(shifougz) ) {
    		boolean operation = yongHuDao.addMemberCount(dingdan.getShanghuid());
    		
    		if ( !operation )
    			return this.getFailJsonResult("【支付】关注商户失败");
    		
    		zh.setShifougz("1");
    	}
        
        zh.setYue(yue);
        zh.setZongxf(new BigDecimal(Double.toString(zh.getZongxf())).add(new BigDecimal(Double.toString(dingdan.getJine()))).doubleValue());
        
        zhangHuDao.update(zh);

        // 添加订单
        dingdan.setGerenid(yonghum);
        dingdan.setYue(zh.getYue());
        dingdan.setLeixing("2");
        dingdan.setShijian(new Date());
        
        dingDanDao.add(dingdan);

        // 推送和短信不在事务范围内
        try {
			// 发送短信
        	String m = shoujih;
        	String c = "您已在“"+sh.getDianming()+
			        "”消费"+dingdan.getJine()+"元，账户余额"+zh.getYue()+"元 ";
        	
        	m += "," + sh.getShoujih();
        	c += "{|}" + "“" + yh.getYonghum() + 
					"”已在您店内消费"+dingdan.getJine()+"元，账户余额"+zh.getYue()+"元 ";
			
			if(employeePh!=null && !"".equals(employeePh)) {
				m += "," + employeePh;
	        	c += "{|}" + "“" + yh.getYonghum() + 
						"”已在您店内消费"+dingdan.getJine()+"元，账户余额"+zh.getYue()+"元 ";
			}
			SendMsgUtil sms = new SendMsgUtil(m, c);
			new Thread(sms).start();
			
			// 维护推送相关数据
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("shanghuid", zh.getShanghuid());
			param.put("gerenid", zh.getGerenid());
			param.put("grNQCount", zh.getGrNQCount() + 1);
			param.put("shNQCount", zh.getShNQCount() + 1);
			zhangHuDao.updateNQCount(param);

			// 推送给商户
//			TuiSong ts = new TuiSong();
//			param.put("grNQCount", null);
//			Map<String, Integer> count = new HashMap<String, Integer>();
//			count.put(yh.getYonghum(), zhangHuDao.getShNQSum(param));
//			ts.setCount(count);
//			param.put("gerenid", null);
//			ts.setSum(zhangHuDao.getShNQSum(param));
//
//			JSONObject json = JSONObject.fromObject(ts);
//			JpushUtil ju1 = new JpushUtil(sh.getYonghum(), json.toString());
//			new Thread(ju1).start();
			
			// 推送给个人
//			TuiSong ts2 = new TuiSong();
//			param.put("gerenid", zh.getGerenid());
//			param.put("grNQCount", 1);
//			param.put("shNQCount", null);
//			Map<String, Integer> count2 = new HashMap<String, Integer>();
//			count2.put(sh.getYonghum(), zhangHuDao.getGrNQSum(param));
//			ts2.setCount(count2);
//			param.put("shanghuid", null);
//			ts2.setSum(zhangHuDao.getGrNQSum(param));
//
//			JSONObject json2 = JSONObject.fromObject(ts2);
//			JpushUtil ju2 = new JpushUtil(sh.getYonghum(), json2.toString());
//			new Thread(ju2).start();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
    	
        String msg = yh.getNicheng()+"(搜卡号："+yh.getYonghum()+")\n"
                +"消　　费："+dingdan.getJine()+"元\n"
                +"账户余额："+zh.getYue()+"元";
        
        return this.getSuccessJsonResult(msg);
    }

    // 充经验值
    public JsonResult throwExcepshAddJyz(int shanghuid,String shoujih,double jingyanz) throws Exception {
        DingDan dingdan = new DingDan();
        
        YongHu yh = yongHuDao.selectUserByPhone(shoujih);
        if(yh == null) {
            return this.getFailJsonResult("该用户不存在");
        }
        
        // 查找商户
        String yhm = shanghuid + "";
        while(yhm.length() < 5) {
            yhm = "0" + yhm;
        }
        YongHu sh = yongHuDao.selectUserByYonghum(yhm);
        
        // 判断是否为配送员操作
        String employeePh = null;
        if("3".equals(sh.getLeixing())) {
        	Useromrela ur = useromrelaDao.getEnabledEmployee(yhm);
        	if(ur != null) {
        		employeePh = sh.getShoujih();
        		dingdan.setHandlers(sh.getYonghum());
        		shanghuid = Integer.parseInt(ur.getOwnerid());
        		sh = yongHuDao.selectUserByYonghum(ur.getOwnerid());
        	} else {
        		return this.getFailJsonResult("您的客户端已被禁用");
        	}
        }
        
        int gerenid = Integer.parseInt(yh.getYonghum());
        ZhangHu zh = zhangHuDao.query(shanghuid, Integer.parseInt(yh.getYonghum()));
        if(zh == null) { // 如果该账户不存在，则新建未关注账户
            zh = new ZhangHu();
            zh.setShanghuid(shanghuid);
            zh.setGerenid(gerenid);
            zh.setShifougz("0");
            zh.setYue(0);
            zh.setJingyanz(jingyanz);
            zh.setDengji(0);
            zh.setZongxf(0);
            zh.setZhekoul(0);
            zhangHuDao.add(zh);
        } else { // 存在账户则修改账户信息
//            zh.setJingyanz(new BigDecimal(Double.toString(zh.getJingyanz()))
//                .add(new BigDecimal(Double.toString(jingyanz))).doubleValue());
        	zh.setJingyanz(jingyanz);
        }
        updateZhdj(zh);
        dingdan.setLeixing("3");
        dingdan.setJine(jingyanz);
        dingdan.setShanghuid(shanghuid);
        dingdan.setGerenid(gerenid);
        dingDanDao.add(dingdan);

        // 短信不在事务范围内
        try {
			// 发送短信
        	String m = shoujih;
        	String c = "您已在“"+sh.getDianming()+
			        "”充经验值"+jingyanz+"点，等级"+zh.getDengji()+"级 ";
        	
        	m += "," + sh.getShoujih();
        	c += "{|}" + "“" + yh.getYonghum() + 
					"”已在您店内充经验值"+jingyanz+"点，等级"+zh.getDengji()+"级 ";
			
			if(employeePh!=null && !"".equals(employeePh)) {
				m += "," + employeePh;
	        	c += "{|}" + "“" + yh.getYonghum() + 
			    		"”已在您店内充经验值"+jingyanz+"点，等级"+zh.getDengji()+"级 ";
			}
			SendMsgUtil sms = new SendMsgUtil(m, c);
			new Thread(sms).start();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
        
        String msg = yh.getNicheng() + "(搜卡号："+yh.getYonghum()+")\n"
                +"经验值提升"+dingdan.getJine();
        return this.getSuccessJsonResult(msg);
    }

    // 订单删除，将订单逻辑删除，然后将账户数据回滚，发短信提醒
	public JsonResult throwExcepdeleteOrder(int id, String employeeid) throws Exception {
		DingDan dd = dingDanDao.queryObject(id);
		if(dd == null) {
			return this.getFailJsonResult("该订单不存在！");
		}
		if(dd.getDelFlag()!=null && "1".equals(dd.getDelFlag())) {
			return this.getFailJsonResult("该订单已删除！");
		}
		// 若是配送员删除则校验是否为改配送员下订单
		if(employeeid!=null && !"".equals(employeeid)) {
			Date createTime = dd.getShijian();
			Date now = new Date();
			long escapseDay = (now.getTime() - createTime.getTime()) / (24*60*60*1000);
			if(escapseDay > 1) {
				return this.getFailJsonResult("该订单超过24小时不能删除！");
			}
			if(!employeeid.equals(dd.getHandlers())) {
				return this.getFailJsonResult("该订单您不能删除！");
			} else {
				dd.setRevokeemp("3");
			}
		} else {
			dd.setRevokeemp("1");
		}
    	boolean ddb = dingDanDao.deleteObjectById(id);
    	if(!ddb) {
    		logger.error("删除订单失败，id=" + id);
    		return this.getFailJsonResult("系统异常，请重试");
    	}
    	
    	// 维护订单撤销人字段
    	Map<String, Object> paramR = new HashMap<String, Object>();
		paramR.put("id", id);
		paramR.put("revokeemp", dd.getRevokeemp());
    	dingDanDao.updateRevokeemp(paramR);
    	
    	dd.setDelFlag("1");
    	ZhangHu zh = zhangHuDao.query(dd.getShanghuid(), dd.getGerenid());

        // 获取商户
        String shyhm = dd.getShanghuid() + "";
        while(shyhm.length() < 5) {
            shyhm = "0" + shyhm;
        }
        YongHu sh = yongHuDao.selectUserByYonghum(shyhm);

        // 获取个人
        String gryhm = dd.getGerenid() + "";
        while(gryhm.length() < 5) {
        	gryhm = "0" + gryhm;
        }
        YongHu gr = yongHuDao.selectUserByYonghum(gryhm);

        // 推送相关，不在事务范围内
        try {
        	if("0".equals(dd.getShQuery())) {
                Map<String, Object> param = new HashMap<String, Object>();
            	param.put("shanghuid", zh.getShanghuid());
            	param.put("gerenid", zh.getGerenid());
            	param.put("shNQCount", zh.getShNQCount() - 1);
            	zhangHuDao.updateNQCount(param);
            	

            	// 推送给商户
//            	TuiSong ts = new TuiSong();
//            	Map<String, Integer> count = new HashMap<String, Integer>();
//            	count.put(gr.getYonghum(), zhangHuDao.getShNQSum(param));
//            	ts.setCount(count);
//            	param.put("gerenid", null);
//            	ts.setSum(zhangHuDao.getShNQSum(param));
//
//            	JSONObject json = JSONObject.fromObject(ts);
//            	JpushUtil ju = new JpushUtil(sh.getYonghum(), json.toString());
//            	new Thread(ju).start();
        	}
        	if("0".equals(dd.getGrQuery())) {
                Map<String, Object> param = new HashMap<String, Object>();
            	param.put("shanghuid", zh.getShanghuid());
            	param.put("gerenid", zh.getGerenid());
            	param.put("grNQCount", zh.getGrNQCount() - 1);
            	zhangHuDao.updateNQCount(param);

            	// 推送给个人
//            	TuiSong ts = new TuiSong();
//            	Map<String, Integer> count = new HashMap<String, Integer>();
//            	count.put(sh.getYonghum(), zhangHuDao.getGrNQSum(param));
//            	ts.setCount(count);
//            	param.put("shanghuid", null);
//            	ts.setSum(zhangHuDao.getGrNQSum(param));
//            	
//            	JSONObject json = JSONObject.fromObject(ts);
//            	JpushUtil ju = new JpushUtil(sh.getYonghum(), json.toString());
//            	new Thread(ju).start();
        	}
        } catch(Exception e) {
        	logger.error(e.getMessage(), e);
        }
    	
        BigDecimal incomeTotal = BigDecimal.valueOf(dd.getJine()).add(BigDecimal.valueOf(dd.getFreeAmount()));
    	if("1".equals(dd.getLeixing())) { // 反充值
    		zh.setYue(new BigDecimal(Double.toString(zh.getYue())).subtract(incomeTotal).doubleValue());
            zh.setIncomeIntegrate(BigDecimal.valueOf(zh.getIncomeIntegrate()).subtract(incomeTotal).doubleValue());
            zh.setJingyanz(new BigDecimal(Double.toString(zh.getJingyanz())).subtract(new BigDecimal(Double.toString(dd.getJine()))).doubleValue());
            zh.setZongcz(new BigDecimal(Double.toString(zh.getZongcz())).subtract(incomeTotal).doubleValue());
            updateZhdj(zh);

            // 短信不在事务范围内
            try {
				BigDecimal totalInComeAmount = BigDecimal.valueOf(dd.getJine()).add(BigDecimal.valueOf(dd.getFreeAmount()));

				// 给个人发短信
				String m = gr.getShoujih();
	        	String c = "您在“"+sh.getDianming()+
				        "”充值"+totalInComeAmount.doubleValue()+"元已撤销，账户余额"+zh.getYue()+"元，" +
				        "等级"+zh.getDengji()+"级 ";
	        	
	        	String shs = "您已将“"+gr.getYonghum()+
				        "”的"+totalInComeAmount.doubleValue()+"元充值撤销，账户余额"+zh.getYue()+"元，" +
				        "等级"+zh.getDengji()+"级 ";
	        	if(employeeid!=null && !"".equals(employeeid)) {
					YongHu psy = yongHuDao.selectUserByYonghum(dd.getHandlers());
					m += "," + psy.getShoujih();
		        	c += "{|}" + "您已将“"+gr.getYonghum()+
					        "”的"+totalInComeAmount.doubleValue()+"元充值撤销，账户余额"+zh.getYue()+"元，" +
					        "等级"+zh.getDengji()+"级 ";

					shs = gr.getYonghum()+ "”的"+totalInComeAmount.doubleValue()+"元充值已被" + psy.getNicheng()
							+ "撤销，账户余额"+zh.getYue()+"元，" + "等级"+zh.getDengji()+"级 ";
				}
	        	m += "," + sh.getShoujih();
	        	c += "{|}" + shs;
	        	
				SendMsgUtil sms = new SendMsgUtil(m, c);
				new Thread(sms).start();
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
            return this.getSuccessJsonResult("撤销成功");
    	} else if("2".equals(dd.getLeixing())) { // 反消费
    		zh.setYue(new BigDecimal(Double.toString(zh.getYue())).add(new BigDecimal(Double.toString(dd.getJine()))).doubleValue());
            zh.setZongxf(new BigDecimal(Double.toString(zh.getZongxf())).subtract(new BigDecimal(Double.toString(dd.getJine()))).doubleValue());
            updateZhdj(zh);
            
            // 短信不在事务范围内
            try {
            	String m = gr.getShoujih();
	        	String c = "您在“"+sh.getDianming()+
				        "”消费"+dd.getJine()+"元已撤销，账户余额"+zh.getYue()+"元 ";
	        	
	        	String shs = "您已将“"+gr.getYonghum()+ "”的"+dd.getJine()+"元消费撤销，账户余额"+zh.getYue()+"元 ";
	        	if(employeeid!=null && !"".equals(employeeid)) {
					YongHu psy = yongHuDao.selectUserByYonghum(dd.getHandlers());
					m += "," + psy.getShoujih();
		        	c += "{|}" + "您已将“"+gr.getYonghum()
							+ "”的"+dd.getJine()+"元消费撤销，账户余额"+zh.getYue()+"元 ";

					shs = gr.getYonghum()+ "”的"+dd.getJine()+"元消费已被" + psy.getNicheng() + "撤销，账户余额"+zh.getYue()+"元 ";
				}
	        	m += "," + sh.getShoujih();
	        	c += "{|}" + shs;
	        	
				SendMsgUtil sms = new SendMsgUtil(m, c);
				new Thread(sms).start();
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
            
            return this.getSuccessJsonResult("撤销成功");
    	} else { // 反充经验值
    		zh.setJingyanz(new BigDecimal(Double.toString(zh.getJingyanz())).subtract(new BigDecimal(Double.toString(dd.getJine()))).doubleValue());
    		updateZhdj(zh);
    		
    		// 短信不在事务范围内
            try {
            	String m = gr.getShoujih();
	        	String c = "您在“"+sh.getDianming()+
				        "”充经验值"+dd.getJine()+"点已撤销，等级"+zh.getDengji()+"级 ";
	        	
	        	String shs = "您已将“"+gr.getYonghum()+ "”的增加经验值"+dd.getJine()+"点撤销，等级"+zh.getDengji()+"级 ";
	        	if(employeeid!=null && !"".equals(employeeid)) {
					YongHu psy = yongHuDao.selectUserByYonghum(dd.getHandlers());
					m += "," + psy.getShoujih();
		        	c += "{|}" + "您已将“"+gr.getYonghum()
							+ "”的增加经验值"+dd.getJine()+"点撤销，等级"+zh.getDengji()+"级 ";

					shs = gr.getYonghum() + "”的增加经验值"+dd.getJine()+"点已被" + psy.getNicheng() + "撤销，等级"+zh.getDengji()+"级 ";
				}
	        	m += "," + sh.getShoujih();
	        	c += "{|}" + shs;
	        	
				SendMsgUtil sms = new SendMsgUtil(m, c);
				new Thread(sms).start();
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
            return this.getSuccessJsonResult("撤销成功");
    	}
	}

	// 维护账户的折扣等级
	private void updateZhdj(ZhangHu zh) throws Exception {
        // 获取折扣
        List<ZheKou> zks = zheKouDao.queryObjectByJyz(zh.getShanghuid(), zh.getJingyanz());
        int dengji = 0;
        double zhekoul = 0;
        if(zks != null) {
            for(ZheKou zk : zks) {
                if(zk.getDengji() > dengji) {
                    dengji = zk.getDengji();
                    zhekoul = zk.getZhekoul();
                }
            }
        }
        zh.setDengji(dengji);
        zh.setZhekoul(zhekoul);
        zhangHuDao.update(zh);
    }
	
	public List<DingDan> getOrderList(Map<String, Object> param) throws Exception{
    	return dingDanDao.queryAllList(param);
    }

	/**
	 * 用户获取月订单流水
	 */
	public Map<String, Object> getMonthStream(int gerenid, String year, String updateMonth) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		
		if (updateMonth == null || "".equals(updateMonth.trim())) {
			param.put("updateMonth", "01");
		} else {
			param.put("updateMonth", updateMonth);
		}
		
		param.put("gerenid", gerenid);
		param.put("year", year);

		Double ySaveMoney = dingDanDao.getYSaveMoney(param);
		
		List<MonthStreamJson> monthStreamJsonList = dingDanDao.getMonthStream(param);
		
		updateMonth = "01";
		if (monthStreamJsonList != null && monthStreamJsonList.size() > 0) {
			updateMonth = monthStreamJsonList.get(0).getMonth();
		}
		Calendar cal = Calendar.getInstance();
		Integer curyear = cal.get(Calendar.YEAR);
		if(curyear > Integer.valueOf(year)) {
			updateMonth = "-1";
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("ySaveMoney", ySaveMoney);
		map.put("updateMonth", updateMonth);
		map.put("myList", monthStreamJsonList);
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}

	/**
	 * 用户获取日订单流水
	 */
	public Map<String, Object> getDayStream(int gerenid, String year, String month, String updateDay) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		
		if (updateDay == null || "".equals(updateDay.trim())) {
			param.put("updateDay", "01");
		} else {
			param.put("updateDay", updateDay);
		}
		
		param.put("gerenid", gerenid);
		param.put("year", year);
		param.put("month", month);
		
		List<DingDanJson> dingDanJsonList = dingDanDao.getDayStream(param);
		
		updateDay = "01";
		if (dingDanJsonList != null && dingDanJsonList.size() > 0) {
			updateDay = dingDanJsonList.get(0).getDay();
		}
		Calendar cal = Calendar.getInstance();
		Integer curyear = cal.get(Calendar.YEAR);
		Integer curmonth = cal.get(Calendar.MONTH) + 1;
		if(curyear > Integer.valueOf(year)) {
			updateDay = "-1";
		} else if((curyear.equals(Integer.valueOf(year))) && (curmonth>Integer.valueOf(month))) {
			updateDay = "-1";
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("updateDay", updateDay);
		map.put("myList", dingDanJsonList);
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}
	
	/**
	 * 用户获取订单流水
	 */
	public Map<String, Object> getStream(int gerenid, String date) throws Exception {
		if (date == null || "".equals(date.trim())) {
			Calendar cal = Calendar.getInstance();
			
			String year = cal.get(Calendar.YEAR) + "";
			
			date = year + "-01-01";
		}
		
		String[] ss = date.split("-");
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("gerenid", gerenid);
		param.put("year", ss[0]);
		param.put("updateMonth", ss[1]);
		
		Double ySaveMoney = dingDanDao.getYSaveMoney(param);
		List<MonthStreamJson> monthStreamJsonList = dingDanDao.getMonthStream(param);
		
		MonthStreamJson monthStreamJson = null;
		
		List<DingDanJson> dayList = null;
		
		List<MonthStreamJson> monthList = new ArrayList<MonthStreamJson>();
		
		param.put("gerenid", gerenid);
		param.put("year", ss[0]);
		
		String month = null;
		for (int i = 0; i < monthStreamJsonList.size(); i++) {
			monthStreamJson = monthStreamJsonList.get(i);
			
			month = monthStreamJson.getMonth();
			
			param.put("month", month);
			
			if (Integer.parseInt(month) == Integer.parseInt(ss[1])) {
				param.put("updateDay", ss[2]);
			} else {
				param.put("updateDay", "01");
			}
			
			dayList = dingDanDao.getDayStream(param);
			
			monthStreamJson.setDayList(dayList);
			
			monthList.add(monthStreamJson);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		map.put("date", sdf.format(new Date()));
		map.put("ySaveMoney", ySaveMoney);
		map.put("monthList", monthList);
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}

	/**
	 * 获取商家支出报表
	 */
	public Map<String, Object> getReportByMerchant(int gerenid, String yearAndMonth) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", yearAndMonth);
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("myList", dingDanDao.getReportByMerchant(param));
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}
	
	/**
	 * 获取商家支出报表明细
	 */
	public Map<String, Object> getReportmxByMerchant(int gerenid, String yearAndMonth, 
			String shanghuid, String updateDay) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		
		if (updateDay == null || "".equals(updateDay.trim())) {
			param.put("updateDay", "01");
		} else {
			param.put("updateDay", updateDay);
		}
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", yearAndMonth);
		param.put("shanghuid", shanghuid);
		
		List<DingDanJson> dingDanJsonList = dingDanDao.getReportmxByMerchant(param);
		
		updateDay = "01";
		if (dingDanJsonList != null && dingDanJsonList.size() > 0) {
			updateDay = dingDanJsonList.get(0).getDay();
		}
		String[] ss = yearAndMonth.split("-");
		Calendar cal = Calendar.getInstance();
		Integer curyear = cal.get(Calendar.YEAR);
		Integer curmonth = cal.get(Calendar.MONTH) + 1;
		if(curyear > Integer.valueOf(ss[0])) {
			updateDay = "-1";
		} else if((curyear.equals(Integer.valueOf(ss[0]))) && (curmonth>Integer.valueOf(ss[1]))) {
			updateDay = "-1";
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("updateDay", updateDay);
		map.put("myList", dingDanJsonList);
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}

	/**
	 * 获取类型支出报表
	 */
	public Map<String, Object> getReportByMerchantType(int gerenid, String yearAndMonth) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", yearAndMonth);
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("myList", dingDanDao.getReportByMerchantType(param));
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}

	/**
	 * 获取类型支出报表明细
	 */
	public Map<String, Object> getReportmxByMerchantType(int gerenid, String yearAndMonth, 
			Long merchantTypeid, String updateDay) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		
		if (updateDay == null || "".equals(updateDay.trim())) {
			param.put("updateDay", "01");
		} else {
			param.put("updateDay", updateDay);
		}
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", yearAndMonth);
		param.put("merchantTypeid", merchantTypeid);
		
		List<DingDanJson> dingDanJsonList = dingDanDao.getReportmxByMerchantType(param);
		
		updateDay = "01";
		if (dingDanJsonList != null && dingDanJsonList.size() > 0) {
			updateDay = dingDanJsonList.get(0).getDay();
		}
		String[] ss = yearAndMonth.split("-");
		Calendar cal = Calendar.getInstance();
		Integer curyear = cal.get(Calendar.YEAR);
		Integer curmonth = cal.get(Calendar.MONTH) + 1;
		if(curyear > Integer.valueOf(ss[0])) {
			updateDay = "-1";
		} else if((curyear.equals(Integer.valueOf(ss[0]))) && (curmonth>Integer.valueOf(ss[1]))) {
			updateDay = "-1";
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("updateDay", updateDay);
		map.put("myList", dingDanJsonList);
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}
	
	/**
     * 获取商户报表
     */
	public Map<String, Object> getReport(int gerenid, String date) throws Exception {
		if (date == null || "".equals(date.trim())) {
			Calendar cal = Calendar.getInstance();
			
			String year = cal.get(Calendar.YEAR) + "";
			
			date = year + "-01-01";
		}
		
		String[] ss = date.split("-");
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", ss[0] + "-" + ss[1]);
		
		List<ReportJson> reportJsonList = dingDanDao.getReport(param);
		
		ReportJson reportJson = null;
		
		List<DingDanJson> mxList = null;
		
		List<ReportJson> list = new ArrayList<ReportJson>();
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", ss[0] + "-" + ss[1]);
		param.put("updateDay", ss[2]);
		
		String shanghuid = null;
		for (int i = 0; i < reportJsonList.size(); i++) {
			reportJson = reportJsonList.get(i);
			
			shanghuid = reportJson.getShanghuid();
			
			param.put("shanghuid", shanghuid);
			
			mxList = dingDanDao.getReportmxByMerchant(param);
			
			reportJson.setMxList(mxList);
			
			list.add(reportJson);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		map.put("date", sdf.format(new Date()));
		
		Comparator<ReportJson> comparator = new Comparator<ReportJson>(){
			public int compare(ReportJson r1, ReportJson r2) {
				 if (r1.getPay() > r2.getPay()) {
					 return -1;
				 } else {
					 return 1;
				 }
			}
		};
		
		Collections.sort(list, comparator);
		
		map.put("list", list);
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}
	
	/**
     * 获取商户类型报表
     */
	public Map<String, Object> getReportByType(int gerenid, String date) throws Exception {
		if (date == null || "".equals(date.trim())) {
			Calendar cal = Calendar.getInstance();
			
			String year = cal.get(Calendar.YEAR) + "";
			
			date = year + "-01-01";
		}
		
		String[] ss = date.split("-");
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", ss[0] + "-" + ss[1]);
		
		List<ReportTypeJson> reportTypeJsonList = dingDanDao.getReportByType(param);
		
		ReportTypeJson reportTypeJson = null;
		
		List<DingDanJson> mxList = null;
		
		List<ReportTypeJson> list = new ArrayList<ReportTypeJson>();
		
		param.put("gerenid", gerenid);
		param.put("yearAndMonth", ss[0] + "-" + ss[1]);
		param.put("updateDay", ss[2]);
		
		Long merchantTypeid = null;
		for (int i = 0; i < reportTypeJsonList.size(); i++) {
			reportTypeJson = reportTypeJsonList.get(i);
			
			if (reportTypeJson.getPay().doubleValue() == 0) {
				continue;
			}
			
			merchantTypeid = reportTypeJson.getMerchantTypeid();
			
			param.put("merchantTypeid", merchantTypeid);
			
			mxList = dingDanDao.getReportmxByMerchantType(param);
			
			reportTypeJson.setMxList(mxList);
			
			list.add(reportTypeJson);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		map.put("date", sdf.format(new Date()));
		
		Comparator<ReportTypeJson> comparator = new Comparator<ReportTypeJson>(){
			public int compare(ReportTypeJson r1, ReportTypeJson r2) {
				 if (r1.getPay() > r2.getPay()) {
					 return -1;
				 } else {
					 return 1;
				 }
			}
		};
		
		Collections.sort(list, comparator);
		
		map.put("list", list);
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}

	/**
	 * 获取月节省金额
	 */
	public Map<String, Object> getMSaveMoney(int gerenid, String ym) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("monthSaveMoney", dingDanDao.getMSaveMoney(gerenid, ym));
		
		map.put("result", true);
		map.put("msg", "");
		
		return map;
	}
	
}